function generatePublishSucessPage(itemId) {
    return '<div class="n-result">'
        + '<h3>发布成功！</h3>'
        + '<p><a href="/show?id=' + itemId +'">[查看内容]</a>'
        + '<a href="/">[返回首页]</a></p></div>';
}

(function () {
    //选择上传图片方式事件绑定
    $('input[name="pic"]').change(function () {
        var s, h;
        this.value === "url" ? (s = '#urlUpload', h = '#fileUpload') : (s = '#fileUpload', h = '#urlUpload');
        $(s).css("display", "block");
        $(h).css("display", "none");
    });

    //输入图片链接预览事件绑定
    $('input[name="image"]').on('input', function () {
        $('#imgpre').attr('src', $(this).val());
    });

    //上传图片按钮绑定事件
    $("#upload").click(function () {
        var file = $('#fileUp')[0].files;
        //todo 检查图片大小等操作以及输入框是否合法
        var formData = new FormData();
        formData.append('file', file[0]);
        $.ajax({
            url: '/file/api/upload',
            type: 'POST',
            cache: false,
            data: formData,
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.code === 200) {
                    $('#imgpre').attr('src', data.data);
                    $('input[name="image"]').val(data.data);
                } else {
                    alert("服务器错误，上传失败");
                }
            },
            error: function (data) {
                alert("上传失败,请重试!");
            }
        })
    });

    //提交按钮事件绑定
    $("#public-btn").on('click', (function () {
        var submitData = {
            "name": $('input[name="title"]').val(),
            "remark": $('input[name="summary"]').val(),
            "picAddr": $('input[name="image"]').val(),
            "info": $('textarea[name="detail"]').val(),
            "price": Number($('input[name="price"]').val())
        };
        $.ajax({
            type: 'post',
            url: '/publicSubmit.json',
            data: JSON.stringify(submitData),
            cache: false,
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                if (data.code === 200) {
                    var pageButtomElem = $("#page-buttom");
                    pageButtomElem.empty();
                    pageButtomElem.append(generatePublishSucessPage(data.data));
                } else if (data.code === 300) {
                    alert("没有发布权限");
                } else {
                    alert("服务器错误，发布失败");
                }
            },
            error: function (data) {
                alert("发布失败,请重试!");
            }
        })
    }));
})();
